<script setup lang="ts">
import { ref, watch } from 'vue'
import { refDebounced } from '@vueuse/core'

interface Props {
  presetPeople?: any[]
  dataApi?: (option?: any) => Promise<any>
  keyName?: string
}

const props = withDefaults(defineProps<Props>(), {
  presetPeople: () => {
    return []
  },
  dataApi: () => {
    return new Promise((resolve) => {
      resolve([])
    })
  },
  keyName: 'userId'
})

const emit = defineEmits<{
  (e: 'pick', person: any): void
}>()

const value = ref('')

const keywords = refDebounced(value, 1000)

const visible = ref(false)

const loading = ref(false)

const originData = ref<any[]>([])
console.log(props.presetPeople, props.presetPeople?.length)
if (props.presetPeople?.length) {
  originData.value = [...props.presetPeople]
}

const showData = ref<any[]>([])

watch(keywords, (newVal) => {
  if (newVal) {
    loading.value = false
    if (originData.value?.length) {
      console.log('aaa')
      // 如果预置了用户列表，则本地筛选
      showData.value = originData.value.filter((item: any) => item.userName.includes(newVal))
      loading.value = false
    } else {
      // 如果没有预置用户列表，则从服务端获取
      props
        .dataApi({
          keywords: newVal
        })
        .then((res: any) => {
          showData.value = res
        })
        .finally(() => {
          loading.value = false
        })
    }
  }
})

watch(value, (newVal) => {
  if (newVal) {
    loading.value = true
    visible.value = true
  } else {
    visible.value = false
    showData.value = []
  }
})

const handlePick = (val: any) => {
  value.value = ''
  emit('pick', val)
}
</script>

<template>
  <div class="person-search-wrapper">
    <el-input v-model="value" placeholder="请输入关键字搜索" />
    <div v-if="visible" v-loading="loading" class="result-panel">
      <div v-for="item in showData" :key="item[props.keyName]" class="person-line" @click="handlePick(item)">
        {{ `${item.userName}${item.extra ? `(${item.extra})` : ''}` }}
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.person-search-wrapper {
  width: 90%;
  box-sizing: border-box;
  margin-bottom: 20px;
  position: relative;
  .result-panel {
    @include rect(100%, 420px);
    box-sizing: border-box;
    padding: 10px;
    position: absolute;
    top: calc(100% + 10px);
    background: #ffffff;
    border: 1px solid rgb(220, 223, 230);
    border-radius: 4px;
    overflow: auto;
    z-index: 999;
    .person-line {
      width: 100%;
      box-sizing: border-box;
      border-radius: 4px;
      padding: 10px 0;
      padding-left: 10px;
      display: flex;
      align-items: center;
      cursor: pointer;
      &:hover {
        background: #eeeeee;
      }
    }
  }
}
</style>
